using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraCtl : MonoBehaviour
{
    public float wasdSpeed;
    public float mouseSpeed;

    public float size = 50;
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        //wasd
        wasdCtl();
        //右键
        rightMouseCtl();
        //缩放
        scale();
        //移动限制
        moveLimit();
    }

    //TODO 感觉有点卡
    private void scale()
    {
        float scale = Input.GetAxis("Mouse ScrollWheel");
        if (scale == 0)
        {
            return;
        }

        // float view = Camera.main.fieldOfView;
        // view += scale*size;
        // Camera.main.fieldOfView = Math.Clamp(view, 50, 100);
        float orthographicSize = Camera.main.orthographicSize;
        orthographicSize += scale * size;
        Camera.main.orthographicSize = Math.Clamp(orthographicSize, 4, 10);
    }

    private void moveLimit()
    {
        //1920 : 1080 = 1.7:1
        //相机大小为12，即宽度为24，限制可以左右移动1/4
        //y在-6~6之间
        Vector3 position = transform.position;
        if (Math.Abs(position.z) > 6)
        {
            position.z = position.z < 0 ? -6 : 6;
        }

        //x方向的1/4 = 24*1.7/4 = 10.2
        if (Math.Abs(position.x) > 10.2)
        {
            position.x = position.x < 0 ? -10.2f : 10.2f;
        }

        transform.position = position;
    }

    private Vector3 rightMouseDownPos = Vector3.zero;
    private bool canMoveCamera = false;
    private void rightMouseCtl()
    {
        //鼠标右键 
        Vector3 mousePos = Input.mousePosition;
        if (Input.GetMouseButtonDown(1))
        {
            //检测是否点击在UI上
            rightMouseDownPos = mousePos;
            Debug.Log("pos:"+mousePos);
            canMoveCamera = true;
        }
        if (Input.GetMouseButtonUp(1))
        {
            //检测是否点击在UI上
            canMoveCamera = false;
        }

        if (!canMoveCamera)
        {
            return;
        }

        if (Vector3.Distance(mousePos, rightMouseDownPos) < 0.1)//移动距离太小相机就不移动了，防止抖动
        {
            return;
        }
        
        Vector3 direction = mousePos - rightMouseDownPos;
        rightMouseDownPos = mousePos;
        direction.z = direction.y;
        direction.y = 0;
        direction = -direction.normalized;
        transform.Translate(direction*Time.deltaTime*mouseSpeed,Space.World);
    }

    private void wasdCtl()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if (h == 0 && v == 0)
        {
            return;
        }

        Vector3 direction = new Vector3(h, 0, v).normalized;
        Debug.Log("direction:"+direction);
        transform.Translate(direction*Time.deltaTime*wasdSpeed,Space.World);
    }
    
    
}